package com.sdms.core.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.sdms.core.config.ServerConf;

public class DBConnector
{
	private static String configFilePath = "config/server.conf";
	private static DBConnector connector;
	private ServerConf config;

	public static DBConnector getInstance()
	{
		if ( connector == null )
		{
			connector = new DBConnector();
		}
		return connector;
	}

	private DBConnector()
	{
		JAXBXmlUtil<ServerConf> xmlUtil = new JAXBXmlUtil<ServerConf>();
		config = xmlUtil.readFromXmlFile( configFilePath, ServerConf.class );
	}

	public Connection getConnection()
	{
		Connection conn = null;
		try
		{
			Class.forName( config.getDbClass() );
		}
		catch ( ClassNotFoundException e )
		{
			System.out.println( " Unable to load driver. " );
		}
		try
		{
			conn = DriverManager.getConnection( config.getUrl(), config.getUsername(), config.getPassword() );
			System.out.println( " Connection Established. " );
		}
		catch ( SQLException e )
		{
			System.out.println( " Error connecting to database:  " + e );
		}
		return conn;
	}
	
	public static void close(ResultSet rs)
	{
		if ( rs != null )
		{
			try
			{
				rs.close();
			}
			catch ( SQLException e )
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void close(Statement stmt)
	{
		if ( stmt!=null )
		{
			try
			{
				stmt.close();
			}
			catch ( SQLException e )
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void close(Connection conn)
	{
		if ( conn!=null )
		{
			try
			{
				conn.close();
			}
			catch ( SQLException e )
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}	
}
